import axios from 'axios'
import { getToken } from './auth'

const instance = axios.create({
  timeout: 5000,
  baseURL: 'http://localhost:3009'
})

instance.interceptors.request.use(
  function(config) {
    config.headers.authorization = 'bearer ' + getToken()
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function(response) {
    // console.log(response)
    return response.data
  },
  function(error) {
    // console.dir(error)  查看error里的数据
    if (error.response.status === 401) {
      window.location.href = '/#/login'
    }
    return Promise.reject(error)
  }
)
// 默认导出
export default instance

export function get(url, params) {
  return instance.get(url, { params })
}

export function post(url, data) {
  return instance.post(url, data)
}

export function put(url, data) {
  return instance.put(url, data)
}

export function del(url) {
  return instance.delete(url)
}
